﻿using System;
using System.Collections.Generic;
using System.Reflection;
using BGShell.Components;
using BGShell.Drawing;
using System.Collections;

namespace BGShell.PowerShell.DataTips
{
    internal sealed class TypeLiteralDataTip : StaticMembersDataTip
    {
        public TypeLiteralDataTip(Type type)
            : base(type)
        {
            IconOverlay = TypeModelIconOverlay.None;

            if (type.IsEnum)
            {
                Icon = TypeModelIcon.Enum;
            }
            else if (type.IsValueType)
            {
                Icon = TypeModelIcon.Structure;
            }
            else if (type.IsInterface)
            {
                Icon = TypeModelIcon.Interface;
            }
            else if (type.IsSubclassOf(typeof(Delegate)))
            {
                Icon = TypeModelIcon.Delegate;
            }
        }

        protected override PSObjectRawDataTip Create(Object target, FieldInfo field)
        {
            if (ValueTypeIsEnum)
            {
                return new EnumFieldDataTip(ValueType, field.Name, field.GetValue(target));
            }

            return base.Create(target, field);
        }

        public bool ValueTypeIsEnum
        {
            get
            {
                if (ValueType != null)
                {
                    return ValueType.IsEnum;
                }

                return false;
            }
        }

        public override string Name
        {
            get { return '[' + PSLanguage.FormatTypeName(ValueType) + ']'; }
        }

        public override string ValueAsString
        {
            get
            {
                if (ValueTypeIsEnum)
                {
                    return PSLanguage.FormatTypeName(Enum.GetUnderlyingType(ValueType));
                }

                return base.ValueAsString;
            }
        }

        public override int Compare(DataTipItem x, DataTipItem y)
        {
            if (ValueTypeIsEnum)
            {
                var xe = x as EnumFieldDataTip;
                var ye = y as EnumFieldDataTip;

                if ((xe != null) && (ye != null))
                {
                    unchecked
                    {
                        return Comparer.DefaultInvariant.Compare(xe.Value, ye.Value);
                    }
                }
            }

            return base.Compare(x, y);
        }
    }
}
